package com.feijia.aijingjingus;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.feijia.aijingjingus.util.PreferencesUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

import static com.feijia.aijingjingus.GlobalHelper.GUserNum;
import static com.feijia.aijingjingus.GlobalHelper.md5;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.System.in;
import static java.lang.System.out;

public class signup_Activity extends AppCompatActivity {
    private Button btnSendMsg, btnSubmitCode;
    private EditText etPhoneNumber, etCode,etPassword,etConfirmPassword;
    private String Password,ConfirmPassword,PhoneNum;
    private String countryCode="";
    private int i = 60;//倒计时
    private TextView tvCountryCode;
    private SharedPreferences sp;
    TextView tv86,tv1;
    Context context =this;

    private RadioGroup sexRadioGroup;
    private RadioButton manRadioButton,womanRadioButton;

    Handler  handler = new Handler() {
        public void handleMessage(Message msg) {
            final String[] POSTresult = {""};
            if (msg.what == -1) {
                //修改控件文本进行倒计时  i 以60秒倒计时为例
                btnSendMsg.setText( i+" s");
            } else if (msg.what == -2) {
                //修改控件文本，进行重新发送验证码
                btnSendMsg.setText("Retry");
                btnSendMsg.setClickable(true);
                i = 60;
            } else {
                int event = msg.arg1;
                int result = msg.arg2;
                Object data = msg.obj;
                Log.e("asd", "event=" + event + "  result=" + result + "  ---> result=-1 success , result=0 error");
                if (result == SMSSDK.RESULT_COMPLETE) {
                    // 短信注册成功后，返回MainActivity,然后提示
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        // 提交验证码成功,调用注册接口，之后直接登录
                        //当号码来自短信注册页面时调用登录注册接口
                        //当号码来自绑定页面时调用绑定手机号码接口
                        Runnable run =new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    String url = "http://120.77.255.57/ting/register.php";
                                    PrintWriter out = null;
                                    BufferedReader in = null;


                                    URL realUrl = new URL(url);
                                    // 打开和URL之间的连接
                                    URLConnection conn = realUrl.openConnection();

                                    String method = "POST";
                                    String accept = "application/json";
                                    String content_type = "application/json";
                                    conn.setRequestProperty("content-type", content_type);
                                    conn.setRequestProperty("accept", accept);
                                    conn.setDoOutput(true);
                                    conn.setDoInput(true);
                                    JSONObject requestObj=new JSONObject();
                                    try {
                                        JSONObject root = new JSONObject();
                                        root.put("UserNo", parseLong(PhoneNum));
                                        root.put("UserPassword", Password);
                                        requestObj=root;
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }

                                    String body = requestObj.toString();
                                    System.out.printf("POST PhoneNum:"+requestObj.getLong("UserNo"));
                                    System.out.printf("POST Password:"+requestObj.getString("UserPassword"));
                                    System.out.printf("POST body:"+body);
                                    // 获取URLConnection对象对应的输出流
                                    out = new PrintWriter(conn.getOutputStream());
                                    // 发送请求参数
                                    out.print(body);
                                    // flush输出流的缓冲
                                    out.flush();
                                    // 定义BufferedReader输入流来读取URL的响应
                                    InputStream is;
                                    HttpURLConnection httpconn = (HttpURLConnection) conn;
                                    if (httpconn.getResponseCode() == 200) {
                                        is = httpconn.getInputStream();
                                    } else {
                                        is = httpconn.getErrorStream();
                                    }
                                    InputStreamReader sr = new InputStreamReader(is,"utf-8");
                                    in = new BufferedReader(sr);
                                    String line;
                                    while ((line = in.readLine()) != null) {
                                        POSTresult[0] += line;
                                    }
                                }catch (Exception e){
                                    out.println("发送 POST 请求出现异常！" + e);
                                    e.printStackTrace();
                                }finally {
                                    try {
                                        if (out != null) {
                                            out.close();
                                        }
                                        if (in != null) {
                                            in.close();
                                        }
                                    } catch (IOException ex) {
                                        ex.printStackTrace();
                                    }
                                }
                                // 解析请求结果
                                try {
                                    JSONObject out = new JSONObject(POSTresult[0]);
                                    System.out.printf("POST back:"+out.toString());
                                    if (out.getInt("OperateResult")==1) {
                                        handler.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(context, getString(R.string.RegistrationSuccess), Toast.LENGTH_SHORT).show();
                                            }
                                        });
                                        String OperateMsg = out.getString("OperateMsg"); // 获取操作结果信息
                                        System.out.printf(" OperateResult : %s \n OperateMsg : %s\n", out.getInt("OperateResult"), OperateMsg);
                                        GUserNum  = PhoneNum;
                                        SharedPreferences.Editor editor = sp.edit();
                                        editor.putString("USER_NAME", GUserNum);
                                        editor.apply();
                                        Intent intent =new Intent("TestPI");
                                        //Intent intent =new Intent("controlCenterActivity");
                                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                        startActivity(intent);
                                    } else {
                                        handler.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(context, getString(R.string.RegistrationFailed), Toast.LENGTH_SHORT).show();
                                            }
                                        });
                                        System.out.println("predict error");
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        };
                        new Thread(run).start();

                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        Toast.makeText(getApplicationContext(), getString(R.string.CodeHasSent),
                                Toast.LENGTH_SHORT).show();
                    } else {
                        ((Throwable) data).printStackTrace();
                    }
                } else if (result == SMSSDK.RESULT_ERROR) {
                    try {
                        Throwable throwable = (Throwable)data;
                        throwable.printStackTrace();
                        JSONObject object = new JSONObject(throwable.getMessage());
                        String des = object.optString("detail");//错误描述
                        int status = object.optInt("status");//错误代码
                        if (status > 0 && !TextUtils.isEmpty(des)) {
                            Toast.makeText(signup_Activity.this,"错误代码"+status+":"+ des, Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        //do something
                    }
                }
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sp = this.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        setContentView(R.layout.activity_signup_layout);
        countryCode=getString(R.string.CountryCode);
        if(!GUserNum.equals(""))
        {
            Intent intent =new Intent("TestPI");
            //Intent intent =new Intent("controlCenterActivity");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        }
        Button button9 = (Button)findViewById(R.id.button9);
        button9.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        etPhoneNumber = (EditText) findViewById(R.id.etPhoneNumber);
        etCode = (EditText) findViewById(R.id.etCode);
        etPassword = (EditText) findViewById(R.id.etPassword);
        etConfirmPassword = (EditText) findViewById(R.id.etConfirmPassword);
        btnSendMsg = (Button) findViewById(R.id.btnSendMsg);
        btnSubmitCode = (Button) findViewById(R.id.btnSubmitCode);
        tvCountryCode = (TextView) findViewById(R.id.tvCountryCode);
        tv86 = (TextView)findViewById(R.id.tvc86);
        tv1 = (TextView)findViewById(R.id.tvc1);
        sexRadioGroup = (RadioGroup)findViewById(R.id.sex);
        manRadioButton =(RadioButton)findViewById(R.id.sex_man);
        womanRadioButton =(RadioButton)findViewById(R.id.sex_woman);

        EventHandler eventHandler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        SMSSDK.registerEventHandler(eventHandler);
        btnSendMsg.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                onClickEvent(v);
            }
        });
        btnSubmitCode.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                onClickEvent(v);
            }
        });
        tvCountryCode.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                onClickEvent(v);
            }
        });
        tv1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                onClickEvent(v);
            }
        });
        tv86.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                onClickEvent(v);
            }
        });

        sexRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if(manRadioButton.getId()==i){
                    String sex_man = manRadioButton.getText().toString();
                    Toast.makeText(getApplicationContext(),sex_man ,Toast.LENGTH_SHORT).show();
                }
                if(womanRadioButton.getId()==i){
                    String sex_woman = womanRadioButton.getText().toString();
                    Toast.makeText(getApplicationContext(),sex_woman ,Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    public void onClickLogin(View view)
    {
        startActivity(new Intent("login_Activity"));
    }
    public void onClickEvent(View v)
    {
        PhoneNum = etPhoneNumber.getText().toString().trim();
        Password = etPassword.getText().toString().trim();
        Password = md5(Password);
        ConfirmPassword = etConfirmPassword.getText().toString().trim();
        ConfirmPassword = md5(ConfirmPassword);
        final String[] POSTresult = {""};
        switch (v.getId()) {
            case R.id.btnSendMsg:
                if (TextUtils.isEmpty(PhoneNum)) {
                    Toast.makeText(getApplicationContext(), getString(R.string.PhoneNumberNoEmpty),
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                Log.v("signup PhoneNum:",PhoneNum);
                Log.v("signup countryCode:",countryCode);
                SMSSDK.getVerificationCode(countryCode, PhoneNum);
                btnSendMsg.setClickable(false);
                //开始倒计时
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (; i > 0; i--) {
                            handler.sendEmptyMessage(-1);
                            if (i <= 0) {
                                break;
                            }
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        handler.sendEmptyMessage(-2);
                    }
                }).start();
                break;
            case R.id.btnSubmitCode:
                String code = etCode.getText().toString().trim();
                if (TextUtils.isEmpty(PhoneNum)) {
                    Toast.makeText(getApplicationContext(), getString(R.string.PhoneNumberNoEmpty),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

               /* if (TextUtils.isEmpty(code)) {
                    Toast.makeText(getApplicationContext(), getString(R.string.CodeNoEmpty),
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                /*if (!isMobileNO(etPhoneNumber.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), getString(R.string.NumberError),
                            Toast.LENGTH_SHORT).show();
                    return;
                }*/

                if (Password.isEmpty()||ConfirmPassword.isEmpty()) {
                    Toast.makeText(getApplicationContext(), getString(R.string.PasswordNoEmpty),
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                /*if (Password.compareTo(ConfirmPassword)!=0) {
                    Toast.makeText(getApplicationContext(), getString(R.string.PasswordMustSame),
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                if(!manRadioButton.isChecked()&&!womanRadioButton.isChecked()){
                    Toast.makeText(getApplicationContext(), getString(R.string.sexselect),
                            Toast.LENGTH_SHORT).show();
                    return;
                }*/
                Runnable run =new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String url = "http://120.77.255.57/ting/register.php";
                            PrintWriter out = null;
                            BufferedReader in = null;


                            URL realUrl = new URL(url);
                            // 打开和URL之间的连接
                            URLConnection conn = realUrl.openConnection();

                            String method = "POST";
                            String accept = "application/json";
                            String content_type = "application/json";
                            conn.setRequestProperty("content-type", content_type);
                            conn.setRequestProperty("accept", accept);
                            conn.setDoOutput(true);
                            conn.setDoInput(true);
                            JSONObject requestObj=new JSONObject();
                            try {
                                JSONObject root = new JSONObject();
                                root.put("UserNo", parseLong(PhoneNum));
                                root.put("UserPassword", Password);
                                requestObj=root;
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            String body = requestObj.toString();
                            System.out.printf("POST PhoneNum:"+requestObj.getLong("UserNo"));
                            System.out.printf("POST Password:"+requestObj.getString("UserPassword"));
                            System.out.printf("POST body:"+body);
                            // 获取URLConnection对象对应的输出流
                            out = new PrintWriter(conn.getOutputStream());
                            // 发送请求参数
                            out.print(body);
                            // flush输出流的缓冲
                            out.flush();
                            // 定义BufferedReader输入流来读取URL的响应
                            InputStream is;
                            HttpURLConnection httpconn = (HttpURLConnection) conn;
                            if (httpconn.getResponseCode() == 200) {
                                is = httpconn.getInputStream();
                            } else {
                                is = httpconn.getErrorStream();
                            }
                            InputStreamReader sr = new InputStreamReader(is,"utf-8");
                            in = new BufferedReader(sr);
                            String line;
                            while ((line = in.readLine()) != null) {
                                POSTresult[0] += line;
                            }
                        }catch (Exception e){
                            out.println("发送 POST 请求出现异常！" + e);
                            e.printStackTrace();
                        }finally {
                            try {
                                if (out != null) {
                                    out.close();
                                }
                                if (in != null) {
                                    in.close();
                                }
                            } catch (IOException ex) {
                                ex.printStackTrace();
                            }
                        }
                        // 解析请求结果
                        try {
                            JSONObject out = new JSONObject(POSTresult[0]);
                            System.out.printf("POST back:"+out.toString());
                            if (out.getInt("OperateResult")==1) {
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(context, getString(R.string.RegistrationSuccess), Toast.LENGTH_SHORT).show();

                                    }
                                });
                                String OperateMsg = out.getString("OperateMsg"); // 获取操作结果信息
                                System.out.printf(" OperateResult : %s \n OperateMsg : %s\n", out.getInt("OperateResult"), OperateMsg);
                                GUserNum  = PhoneNum;
                                SharedPreferences.Editor editor = sp.edit();
                                editor.putString("USER_NAME", GUserNum);
                                editor.apply();
                                if(!manRadioButton.isChecked()){
                                    String sexwoman = womanRadioButton.getText().toString();
                                    PreferencesUtils.putString(getApplicationContext(),PreferencesUtils.PREFERENCE_NAME,sexwoman);
                                }else {
                                    String sexman = manRadioButton.getText().toString();
                                    PreferencesUtils.putString(getApplicationContext(),PreferencesUtils.PREFERENCE_NAME,sexman);
                                }
                                Intent intent =new Intent("TestPI");
                                //Intent intent =new Intent("controlCenterActivity");
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(intent);
                                /*Intent intent = new Intent();
                                intent.setClass(getApplicationContext(),TestPI.class);
                                startActivity(intent);*/
                            } else {
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(context, getString(R.string.RegistrationFailed), Toast.LENGTH_SHORT).show();

                                    }
                                });
                                System.out.println("predict error");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };
                new Thread(run).start();
                SMSSDK.submitVerificationCode(countryCode, PhoneNum, code);
                break;
            case R.id.tvCountryCode:
                //选择全部国家用的代码
                Intent intent = new Intent(signup_Activity.this, CountryCodeActivity.class);
                startActivityForResult(intent, 0);


                if (tv1.getVisibility()==View.VISIBLE || tv86.getVisibility()==View.VISIBLE)
                {
                    tv1.setVisibility(View.GONE);
                    tv86.setVisibility(View.GONE);
                    tvCountryCode.setBackgroundResource(R.drawable.signupshape);
                } else{
                    if(countryCode.equals("86")) {
                        tv1.setVisibility(View.VISIBLE);
                    } else {
                        tv86.setVisibility(View.VISIBLE);
                    }
                    tvCountryCode.setBackgroundResource(R.drawable.signup_country_shape);
                }
                break;
            case R.id.tvc1:
                tvCountryCode.setBackgroundResource(R.drawable.signupshape);
                countryCode="1";
                tvCountryCode.setText(tv1.getText());
                tv1.setVisibility(View.GONE);
                break;
            case R.id.tvc86:
                tvCountryCode.setBackgroundResource(R.drawable.signupshape);
                countryCode="86";
                tvCountryCode.setText(tv86.getText());
                tv86.setVisibility(View.GONE);
                break;
            default:
                break;
        }

    }
    protected void onDestroy() {
        super.onDestroy();
        // 销毁回调监听接口
        SMSSDK.unregisterAllEventHandler();
    }
    public void onClickBack(View view)
    {
        finish();
    }

    //使用正则表达式判断电话号码
    /*public static boolean isMobileNO(String tel) {
        Pattern p = Pattern.compile("^(13[0-9]|15([0-3]|[5-9])|14[5,7,9]|17[1,3,5,6,7,8]|18[0-9])\\d{8}$");
        Matcher m = p.matcher(tel);
        System.out.println(m.matches() + "---");
        return m.matches();
    }*/

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null)
            return;
        Bundle bundle = data.getExtras();
        String country = bundle.getString("country");
        countryCode = bundle.getString("countryCode");
        if (resultCode == 1) {
            tvCountryCode.setText( "+ " + countryCode);
        }
    }

}
